package com.qfedu.springboot1.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qfedu.springboot1.entity.Question;
import com.qfedu.springboot1.service.CharacterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/10/31 16:26
 * @Modified:
 */
@Slf4j
@Service
public class CharacterServiceImpl implements CharacterService {
    private List<Question> questions;
    private Integer currIndex=0;
    /**
     * 聚合数据 申请账号 申请对应的接口：性格测试*/
    private String key="";

    @Override
    public Question queryQuestions() {
        //请求接口 http://apis.juhe.cn/fapig/character_test/questions
        questions=new ArrayList<>();
        //1.准备参数
        Map<String,Object> param=new HashMap<>();
        param.put("key",key);
        //2.发起请求 获取响应
        String json= HttpUtil.get("http://apis.juhe.cn/fapig/character_test/questions",param);
        if(StringUtils.hasLength(json)){
            //3.解析结果
            JSONArray array=new JSONObject(json).getJSONArray("result");
            for (int i = 0; i < array.size(); i++) {
                JSONObject jo=array.getJSONObject(i);
                questions.add(new Question(jo.getStr("q"),jo.getStr("a"),jo.getStr("b"),
                        jo.getStr("ia"),jo.getStr("ib")));
            }
            log.info("本次获取的试题：{}",questions);
        }

        return questions.get(currIndex);
    }

    @Override
    public Question answerQuestion(String answer) {
        if(currIndex<questions.size()-1){
            //不是最后一道
            Question question=questions.get(currIndex);
            if(answer.equals("a"))
            {
                question.setAnswer(question.getAnswerA());
            }else if(answer.equals("b")){
                question.setAnswer(question.getAnswerB());
            }
            currIndex++;
            return questions.get(currIndex);
        }
        return null;
    }

    @Override
    public String queryResult() {
        //提交
        StringBuffer answers=new StringBuffer();
        for (Question q:questions){
            answers.append(q.getAnswer()+",");
        }
        answers.deleteCharAt(answers.length()-1);

        //1.准备参数
        Map<String,Object> param=new HashMap<>();
        param.put("key",key);
        param.put("answers",answers.toString());
        //2.发起请求 获取响应
        return HttpUtil.get("http://apis.juhe.cn/fapig/character_test/analysis",param);
    }
}
